<template>
  <el-form label-width="100px" ref="ruleFormRef" :model="skuInfo" :rules="skuRules">
    <el-form-item label="SPU名称">
      <span>{{ props.SpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number
        class="mx-4"
        style="width: 100%"
        :min="1"
        :max="10"
        controls-position="right"
        v-model="skuInfo.price"
      />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        style="width: 100%"
        class="mx-4"
        controls-position="right"
      />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(attr, index) in AttrList"
          :key="attr.id"
          :md="12"
          :sm="12"
          :lg="8"
        >
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]">
              <el-option
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
                :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                :label="attrValue.valueName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <!-- 销售属性下拉框 -->
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(SaleAttr, index) in SaleAttrList"
          :key="SaleAttr.id"
          :md="12"
          :sm="12"
          :xs="24"
          :lg="8"
        >
          <el-form-item :label="SaleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]">
              <el-option
                v-for="SaleAttrValue in SaleAttr.spuSaleAttrValueList"
                :key="SaleAttrValue.id"
                :value="`${SaleAttr.id}:${SaleAttr.saleAttrName}:${SaleAttrValue.id}:${SaleAttrValue.saleAttrValueName}`"
                :label="SaleAttrValue.saleAttrValueName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <!-- 图片列表 -->
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table border :data="ImageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <el-image
              style="width: 100px; height: 100px"
              :alt="row.imgName"
              :src="row.imgUrl"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              v-if="row.isDefault === '0'"
              @click="setDefaultImage(row)"
              >设置为默认项</el-button
            >
            <el-button type="success" v-else disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="emits('changeValue', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {};
</script>
<script lang="ts" setup>
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu";
import { reqSaveSkuInfo, reqGetSkuListData } from "@/api/product/sku";
import { reqGetAttrListData } from "@/api/product/attr";
import { useCategoryStore } from "@/stores/categoryList";
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
// 创建store对象实列
const categoryStore = useCategoryStore();

// 接收自定义属性传过来的值
const props = defineProps(["SpuInfo"]);
// console.log(props);

// 自定义事件
const emits = defineEmits(["changeValue"]);

// 定义变量 接收请求回来的数据
const ImageList = ref([]);
const SaleAttrList = ref([]);
const AttrList = ref([]);

interface User {
  date: string;
  name: string;
  address: string;
}

const skuInfo = reactive({
  // spu名称
  skuName: "",
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: "",
  // 默认图片
  skuDefaultImg: "",
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
});

// const formSize = ref("default");
// 规则校验
const ruleFormRef = ref<FormInstance>();

//自定义规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  if (value.length == 0) {
    callback("至少添加一张照片");
    return;
  }
  callback(); //什么都不写表示放行通过校验
};
// 校验规则
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: "请输入sku名称", trigger: "blur" },
    { min: 1, max: 10, message: "长度在1到10之间", trigger: "blur" },
  ],
  price: [{ required: true, message: "请输入sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入sku描述", trigger: "blur" }],
  skuAttrValueList: [
    // 平台属性校验规则
    {
      required: true,
      message: "请至少选择一个平台属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      message: "请至少选择一个销售属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuImageList: [{ required: true, validator: skuImageListValidate, trigger: "change" }],
});

// 表单提交之前校验
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      skuInfo.spuId = props.SpuInfo.id;
      skuInfo.category3Id = props.SpuInfo.category3Id;
      // 先过滤为空的下拉框 在将有value的下拉框的value转换成正确格式
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map((item) => {
        const [attrId, attrName, valueId, valueName] = item.split(":");
        return {
          attrId,
          attrName,
          valueId,
          valueName,
        };
      });
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName,
          ] = item.split(":");
          return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName,
          };
        });

      // 数据处理完成后发送请求
      await reqSaveSkuInfo(skuInfo);
      emits("changeValue", 1);
      ElMessage.success("添加sku数据成功...");
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 2添加默认照片属性
const setDefaultImage = (row) => {
  // 将数组中每一项添加一个isDefault属性
  ImageList.value.forEach((item) => {
    item.isDefault = "0"; //此时为0
  });
  row.isDefault = "1";
};

// 3手机列表项
const handleSelectionChange = (val: any) => {
  // val就是我们存储选中照片的数组
  // 将表格中选中的照片获取
  skuInfo.skuImageList = val;
};

//4添加skuInfor,内部校验2

// 当组件挂载时执行逻辑
onMounted(async () => {
  let id = props.SpuInfo.id;

  console.log("skuForm传过来的数据", props.SpuInfo);

  // 当组件挂载时要发送的请求 三级导航 图片数组数据 平台上平属性数据
  const [resSpuImageList, resSpuSaleAttrList, resAttrList] = await Promise.allSettled([
    reqGetSpuImageList(id),
    reqGetSpuSaleAttrList(id),
    reqGetAttrListData({
      category1Id: categoryStore.category1Id as number,
      category2Id: categoryStore.category2Id as number,
      category3Id: categoryStore.category3Id as number,
    }),
  ]);
  console.log(resSpuImageList, resSpuSaleAttrList, resAttrList);
  // 存储数据
  if (resSpuImageList?.status == "fulfilled") {
    // 存储照片数组
    ImageList.value = resSpuImageList.value.map((item) => {
      return {
        ...item, //运来照片数组中存储的属性
        isDefault: "0", // 0 表示正常显示 1 表示默认项
      };
    });
  }

  if (resSpuSaleAttrList?.status == "fulfilled") {
    // 存储属性数组
    SaleAttrList.value = resSpuSaleAttrList.value;
  }
  if (resAttrList?.status == "fulfilled") {
    // 存储三级导航数据
    AttrList.value = resAttrList.value;
  }
});
</script>

<style></style>
